package com.jason.fingerprint.ui;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.PhotoManagerAdapter;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.BitmapHelper;
import com.jason.fingerprint.common.DateFormat;
import com.jason.fingerprint.common.FileHelper;
import com.jason.fingerprint.widget.TitleBar;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.activity.BaseActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: PhotoManagerActivity
 * @Description: 拍照以及照片管理
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015年12月3日10:18:29
 */
public class PhotoManagerActivity extends BaseActivity {

    private static final String TAG = PhotoManagerActivity.class.getSimpleName();
    public static final String KEY_SHOW_CAMERA = "key_show_camera";
    public static final String KEY_SHOW_PHOTO = "key_show_photo";
    public static final String KEY_SHOW_COUNT = "key_show_count";

    private static final int REQUEST_TAKE_PHOTO_OK = 10;

    private TitleBar mTitleBar;
    private GridView mGridView;
    private PhotoManagerAdapter mAdapter;
    private List<String> mPhotos = new ArrayList<String>();
    private File mTakePhotoFile;

    private KJDB mKjdb;

    private boolean mIsShowCamera = true;

    private List<String> mShowPhotos = new ArrayList<String>();

    private int mCount = 5;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_photo_manager);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 3;

        mKjdb = AppContext.getInstance().getKjdb();
        mGridView = (GridView) findViewById(R.id.photo_manager_grid);
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.bindActivity(this);
        mTitleBar.setFunctionOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPhotos != null && !mPhotos.isEmpty() && (mIsShowCamera ? (mPhotos.size() > 1) : (mPhotos.size() > 0))) {
                    if ("管理".equals(mTitleBar.getFunctionView().getText().toString())) {
                        mTitleBar.updateFunctionState(View.VISIBLE, "取消");
                        mAdapter.addAll(mPhotos, true,mIsShowCamera);
                    } else {
                        mTitleBar.updateFunctionState(View.VISIBLE, "管理");
                        mAdapter.addAll(mPhotos, false,mIsShowCamera);
                    }
                } else {
                    mAdapter.addAll(mPhotos, false,mIsShowCamera);
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        mCount = getIntent().getIntExtra(KEY_SHOW_COUNT,1);
        mIsShowCamera = getIntent().getBooleanExtra(KEY_SHOW_CAMERA,true);
        mShowPhotos = getIntent().getStringArrayListExtra(KEY_SHOW_PHOTO);

        mAdapter= new PhotoManagerAdapter(this,mIsShowCamera);
        mGridView.setAdapter(mAdapter);
        if (mIsShowCamera){
            mPhotos.add(PhotoManagerAdapter.CAMERA);
        }
        if (mShowPhotos != null && !mShowPhotos.isEmpty()){
            mPhotos.addAll(mShowPhotos);
        }
        mAdapter.addAll(mPhotos, false,mIsShowCamera);
        updateTitleFunctionState();
    }


    //刷新标题栏状态
    private void updateTitleFunctionState(){
        if(mPhotos != null && !mPhotos.isEmpty() && (mIsShowCamera ? (mPhotos.size() > 1) : (mPhotos.size() > 0))){
            mTitleBar.updateFunctionState(View.VISIBLE,"管理");
        }else{
            mTitleBar.updateFunctionState(View.GONE,"取消");
        }
        mAdapter.addAll(mPhotos, false,mIsShowCamera);
    }

    // 获取拍照
    public void doTakePhoto() {
        if (mPhotos != null && !mPhotos.isEmpty() && mPhotos.size() > mCount){
            Toast.makeText(this, "照片不能超过" + mCount + "张", Toast.LENGTH_SHORT).show();
            return;
        }
        mTakePhotoFile = FileHelper.getPhotoFile(this);
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, mTakePhotoFile.getName());
        values.put(MediaStore.Images.Media.DESCRIPTION, "Image from Android Emulator");
        values.put(MediaStore.Images.Media.DATA, mTakePhotoFile.getPath());
        Uri photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO_OK);
    }

    //查看图片
    public void lookPhoto(int position){
        Intent mIntent = new Intent(PhotoManagerActivity.this, PreviewPhotoActivity.class);
        mIntent.putStringArrayListExtra("images", (new ArrayList<String>(mPhotos)));
        mIntent.putExtra("position", position);
        startActivity(mIntent);
    }

    //删除指定照片
    public void deletePhoto(String path){
        FileHelper.deleteFile(path);
        try{
            mPhotos.remove(path);
            mKjdb.deleteByWhere(ImageOrAudioBean.class,"filePath = '" + path + "'");
        } catch (Exception e){
            e.printStackTrace();
        }
        updateTitleFunctionState();
        mAdapter.addAll(mPhotos, true,mIsShowCamera);
        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, ">>>>>>>>onActivityResult requestCode:" + requestCode + ",resultCode:" + resultCode);
        if (requestCode == REQUEST_TAKE_PHOTO_OK && resultCode == RESULT_OK){
            String path = null;
            if (mTakePhotoFile != null){
                path = mTakePhotoFile.getAbsolutePath();
            }else {
                path = FileHelper.getTheNewPhotoPath(this);
            }

            Log.i(TAG, "-----onActivityResult path" + path);
            if (!TextUtils.isEmpty(path)) {
                try{
                    BitmapHelper.drawDateBitmap(this,path,new SimpleDateFormat(DateFormat.DATE_YMD_HMS).format(new Date(System.currentTimeMillis())));
                }catch (Exception e){
                    e.printStackTrace();
                }
                mPhotos.add(path);
            }
            updateTitleFunctionState();
        }
    }

}
